import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import type { RegisterFormData, StepInfo } from '../types'

export const useRegister = () => {
	const currentStep = ref(1)
	const loading = ref(false)
	const sendingCode = ref(false)
	const countdown = ref(0)

	// 表单数据
	const formData = reactive<RegisterFormData>({
		phone: '',
		verifyCode: '',
		realName: '',
		idCard: '',
		faceVerifyStatus: 'pending',
		password: '',
		confirmPassword: ''
	})

	// 步骤配置
	const steps: StepInfo[] = [
		{
			title: '手机号验证',
			description: '请输入您的手机号码'
		},
		{
			title: '身份信息验证',
			description: '请填写真实姓名和身份证号'
		},
		{
			title: '人脸验证',
			description: '请进行人脸识别验证'
		},
		{
			title: '设置密码',
			description: '设置您的登录密码'
		},
		{
			title: '注册完成',
			description: '恭喜您已成功注册'
		}
	]

	// 验证码倒计时
	const startCountdown = () => {
		countdown.value = 60
		const timer = setInterval(() => {
			countdown.value--
			if (countdown.value <= 0) {
				clearInterval(timer)
			}
		}, 1000)
	}

	// 发送验证码
	const sendVerifyCode = async () => {
		if (!formData.phone) {
			ElMessage.warning('请输入手机号码')
			return
		}

		if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
			ElMessage.warning('请输入正确的手机号码')
			return
		}

		try {
			sendingCode.value = true
			// 模拟发送验证码
			await new Promise(resolve => setTimeout(resolve, 1000))
			ElMessage.success('验证码发送成功')
			startCountdown()
		} catch (error) {
			ElMessage.error('验证码发送失败，请重试')
		} finally {
			sendingCode.value = false
		}
	}

	// 人脸验证
	const startFaceVerify = async () => {
		try {
			loading.value = true
			formData.faceVerifyStatus = 'pending'

			// 模拟人脸验证过程
			await new Promise(resolve => setTimeout(resolve, 3000))

			formData.faceVerifyStatus = 'success'
			ElMessage.success('人脸验证成功')

			// 自动进入下一步
			setTimeout(() => {
				nextStep()
			}, 1000)
		} catch (error) {
			formData.faceVerifyStatus = 'failed'
			ElMessage.error('人脸验证失败，请重试')
		} finally {
			loading.value = false
		}
	}

	// 下一步
	const nextStep = () => {
		if (currentStep.value < 5) {
			currentStep.value++
		}
	}

	// 上一步
	const prevStep = () => {
		if (currentStep.value > 1) {
			currentStep.value--
		}
	}

	// 完成注册
	const completeRegister = async () => {
		try {
			loading.value = true
			// 模拟提交注册
			await new Promise(resolve => setTimeout(resolve, 2000))
			ElMessage.success('注册成功')
			nextStep()
		} catch (error) {
			ElMessage.error('注册失败，请重试')
		} finally {
			loading.value = false
		}
	}

	return {
		currentStep,
		loading,
		sendingCode,
		countdown,
		formData,
		steps,
		sendVerifyCode,
		startFaceVerify,
		nextStep,
		prevStep,
		completeRegister
	}
}
